package server.datasource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import server.dao.util.DatabaseConstants;
import server.idatasource.IRightDataSource;

public class RightDataSource implements IRightDataSource {

	private Connection	connection;

	private Connection getConnection() {

		try {
			Class.forName("org.gjt.mm.mysql.Driver").newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			connection = DriverManager.getConnection(DatabaseConstants.URL, DatabaseConstants.USERNAME, DatabaseConstants.PASSWORD);
		} catch (Exception e) {
			return null;
		}
		return connection;
	}

	@Override
	public String insertRight(int rightId, String rightName) {
		Statement statement = null;
		String command = "";
		String error = "OK";

		try {
			connection = getConnection();
			statement = connection.createStatement();
			command = "INSERT INTO " + DatabaseConstants.RIGHT_TABLE + "VALUES (" + rightId + "," + rightName + ")";
			statement.executeUpdate(command);
		} catch (Exception e) {
			error = e.toString();
		} finally {
			try {
				connection.close();
				statement.close();
			} catch (Exception e) {
				error = e.toString();
			}
		}
		return error;
	}

	@Override
	public String deleteRight(int rightID) {
		Statement statement = null;
		String command = "";
		String error = "OK";

		try {
			connection = getConnection();
			statement = connection.createStatement();
			command = "DELETE FROM " + DatabaseConstants.RIGHT_TABLE + " WHERE " + DatabaseConstants.RIGHT_TABLE_RIGHTID + " = " + rightID;
			statement.executeUpdate(command);
		} catch (Exception e) {
			error = e.toString();
		} finally {
			try {
				connection.close();
				statement.close();
			} catch (Exception e) {
				error = e.toString();
			}
		}
		return error;
	}

	@Override
	public String updateRight(int rightId, String rightName) {
		Statement statement = null;
		String command = "";
		String error = "OK";

		try {
			connection = getConnection();
			statement = connection.createStatement();
			command = "UPDATE " + DatabaseConstants.RIGHT_TABLE + " SET " + DatabaseConstants.RIGHT_TABLE_RIGHTID + " = " + rightId + ", " + DatabaseConstants.RIGHT_TABLE_RIGHT_NAME + "= '" + rightName
					+ "' WHERE " + DatabaseConstants.RIGHT_TABLE_RIGHTID + " = " + rightId;
			statement.executeUpdate(command);
		} catch (Exception e) {
			error = e.toString();
		} finally {
			try {
				connection.close();
				statement.close();
			} catch (Exception e) {
				error = e.toString();
			}
		}
		return error;
	}

}
